<template>
	<div class="mg-tb">
		<!-- 实现评论数据提交到服务器的静态结构 -->
		<div id="postcomment">
			<h3>提交评论</h3>
			<p class="p"></p>
			<textarea placeholder="请输入评论内容..." v-model="postcontent"></textarea>
			<mt-button type="primary" size="large" @click="postcomment">发表</mt-button>
		</div>
	
		<!-- 获取评论数据列表 -->
		<div id="list">
			<h3>评论列表</h3>
			<p class="p"></p>
			<div v-for="(item,index) in list">
				<div class="title">
					<span>第{{index+1}}楼：</span>
					<span>用户：{{item.user_name}}</span>
					<span>发表时间：{{item.add_time | datefmt('YYYY-MM-DD HH:mm:ss')}}</span>
				</div>
				<ul class="mui-table-view">
					<li class="mui-table-view-cell" v-text="item.content"></li>
				</ul>
			</div>
		</div>
	
		<!--3.实现获取更多按钮-->
		<mt-button type="danger" size="large" plain @click="getmore">加载更多评论</mt-button>
	</div>
</template>

<script>
import { Toast } from 'mint-ui';
import common from '../../kits/Common.js';
export default {
	data() {
		return {
			pageindex: 1,
			postcontent: '',	//获取用户的评论内容
			list: []
		}
	},
	created() {
		this.getcomment(this.pageindex);
	},
	props: ['id'],	//用来接收父组件传入的id值
	methods: {
		// 加载跟多评论
		getmore() {
			this.pageindex++;
			// 获取当前this.pageindex值对应的分页数据
			this.getcomment(this.pageindex);
		},
		//评论数据的提交
		postcomment() {
			//判断用户是否输入内容，没有就提醒
			if (this.postcontent.trim().length <= 0) {
				Toast('评论内容不能为空');
				return;
			}
			// /api/postcomment/:artid
			var url = common.apidomain + '/api/postcomment/' + this.id;
			this.$http.post(url, { content: this.postcontent }, { emulateJSON: true }).then(function (res) {
				Toast(res.body.message);
				//将最新的评论追加到评论列表的最顶部
				this.list = [
					{
						"user_name": "匿名用户",
						"add_time": new Date(),
						"content": this.postcontent
					}
				].concat(this.list);
				//评论完就文本框清空
				this.postcontent = "";
			});
		},
		getcomment(pageindex) {
			pageindex = pageindex || 1;
			var url = common.apidomain + '/api/getcomments/' + this.id + '?pageindex=' + pageindex;
			this.$http.get(url).then(function (res) {
				var body = res.body;
				if (body.status != 0) {
					Toast(body.message);
					return
				}
				//利用concat方法链接当前的数组以及服务器返回来的新数组（body.message）
				this.list = this.list.concat(body.message);
			})
		}
	}
}
</script>

<style scoped>
#postcomment {
	padding: 5px;
}

#postcomment .p {
	height: 1px;
	width: 100%;
	background-color: #eee;
}

.title {
	background-color: #eee;
	padding: 5px;
	font-size: 15px;
	color: #666;
}

#list {
	padding: 5px;
}
</style>